package com.stars.easyms.base.pointcut;

import com.stars.easyms.base.util.AnnotationUtil;
import org.springframework.aop.support.AopUtils;
import org.springframework.aop.support.StaticMethodMatcher;
import org.springframework.lang.NonNull;
import org.springframework.util.Assert;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * <p>className: EasyMsAnnotationMethodMatcher</p>
 * <p>description: 支持spring4.x.x版本的注解方法匹配类</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-07-10 15:34
 */
public class EasyMsAnnotationMethodMatcher extends StaticMethodMatcher {

    private final Class<? extends Annotation> annotationType;

    private final boolean checkInherited;

    public EasyMsAnnotationMethodMatcher(Class<? extends Annotation> annotationType, boolean checkInherited) {
        Assert.notNull(annotationType, "Annotation type must not be null");
        this.annotationType = annotationType;
        this.checkInherited = checkInherited;
    }

    @Override
    public boolean matches(@NonNull Method method, @NonNull Class<?> targetClass) {
        if (matchesMethod(method)) {
            return true;
        }
        if (Proxy.isProxyClass(targetClass)) {
            return false;
        }
        Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
        return (specificMethod != method && matchesMethod(specificMethod));
    }

    private boolean matchesMethod(Method method) {
        return (this.checkInherited ? AnnotationUtil.hasAnnotation(method, this.annotationType) :
                method.isAnnotationPresent(this.annotationType));
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        if (!(other instanceof EasyMsAnnotationMethodMatcher)) {
            return false;
        }
        EasyMsAnnotationMethodMatcher otherMm = (EasyMsAnnotationMethodMatcher) other;
        return this.annotationType.equals(otherMm.annotationType) && this.checkInherited == otherMm.checkInherited;
    }

    @Override
    public int hashCode() {
        return this.annotationType.hashCode() * 41 + (checkInherited ? 1 : 0);
    }

    @Override
    public String toString() {
        return getClass().getName() + ": annotationType[" + this.annotationType + "], checkInherited[" + this.checkInherited + "]";
    }

}